package com.qf.business.system.controller;


import com.qf.business.system.service.EmployeeService;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import com.qf.data.system.entity.Employee;
import com.qf.data.system.vo.output.EmployeeOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;

//RestController包含了@ResponseBody,所以方法默认为打了@ResponseBody
@RestController
@RequestMapping("/emp")
@Slf4j
@SessionAttributes("login_emp")
@Validated
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/login")
    public R login(@NotBlank(message = "用戶名不能為空") String username,
                   @NotBlank(message = "密碼不能為空") String password,
                   Model model, HttpSession session) {
        log.info("[emp login] 登录成功！-{}-{}", username, password);
        Employee emp = employeeService.login(username, password);
        if (emp != null) {
            model.addAttribute("login_emp", emp);
            EmployeeOutput employeeOutput = new EmployeeOutput();
            BeanUtils.copyProperties(emp, employeeOutput);
            return Rs.create(employeeOutput);
        }
        return Rs.createFail(Codes.LOGIN_ERROR);
    }

    @RequestMapping("/loginout")
    public R loginOut(SessionStatus sessionStatus) {
        sessionStatus.setComplete();
        return Rs.create("succ");
    }
}
